package com.fang.security.security.handler;

import com.alibaba.fastjson.JSON;
import com.fang.security.common.CommonConstants;
import com.fang.security.common.base.ServiceCode;
import com.fang.security.common.result.JsonResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description 匿名用户访问(未登录)无权限资源时的异常
 * @Author Bernie
 * @Date 2024/4/23 10:45
 **/
@Component
public class CustomizeAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
        JsonResult result = JsonResult.fail(ServiceCode.USER_NOT_LOGIN);
        httpServletResponse.setContentType(CommonConstants.CommonResponse.JSON_U8_CONTENT_TYPE);
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}
